import '@/js/common/router'
import '@/js/layui_exts/admin.js'
import '@/css/common.less'
import '/public/iconfont/iconfont.css'

layui.use(() => {
    const $ = layui.jquery, admin = layui.admin, element = layui.element, util = layui.util, form = layui.form
    admin.isLogin()

    /*渲染：菜单*/
    let renderSubMenu = children => children ? (children.reduce((p, c) => {
            p += '<dd><a href="#' + c.path + '">&#12288;&nbsp;' + c.name + '</a></dd>'
            return p
        }, '<dl class="layui-nav-child">') + '</dl>') : '',
        renderMenu = menu => menu?.reduce((p, c) => {
            p += '<li class="layui-nav-item">\n' +
                '    <a href="' + (c.path ? '#' + c.path : 'javascript:;') + '"><i class="' + c.icon + '"></i>&nbsp;' + c.name + '</a>\n' +
                renderSubMenu(c.children) +
                '</li>'
            return p
        }, ''),
        navUl = $('.layui-layout-admin>.layui-side>.layui-side-scroll>.layui-nav-side'),
        triggerRouter = a => {
            a.trigger('click')
            let p = a.parent().parent().parent()
            if (p.hasClass('layui-nav-item') && !p.hasClass('layui-nav-itemed'))
                p.addClass('layui-nav-itemed')
            if (a.attr('href').startsWith('#/'))
                window.location.href = window.location.origin + window.location.pathname + a.attr('href')
        },
        triggerFirstMenu = () => {
            let level1Menu = navUl.children('li')
            if (level1Menu.length > 0) {
                triggerRouter(level1Menu.first().children('a').first())
                let level2Menu = level1Menu.first().children('dl')
                if (level2Menu.length > 0)
                    triggerRouter(level2Menu.children('dd').children('a').first())

            }
        }

    /*请求：用户信息*/
    admin.get('sys/user/info', undefined, ({data: {user, menu, api}}) => {
        $('#user>i').first().addClass('layui-icon-' + user.sex)
        $('#user>span').text(user.realname)
        admin.setUser(user)
        admin.setPerm(api)

        if (user.footer) {
            admin.setFooter(user.footer)
            form.val('footer-form-filter', {'footer': 'on'})
        } else
            admin.setFooter(false)

        navUl.html(renderMenu(menu))
        element.render('nav', 'menu-nav-filter')

        let hash = window.location.hash
        if (hash.startsWith('#/'))
            triggerRouter($('a[href="' + hash + '"]'))
        else
            triggerFirstMenu()
    })

    /*点击：锁屏*/
    $('#lock-screen').parent('li').click(() => admin.lockScreen())

    /*点击：主页右上角设置*/
    util.on({
        'seting': () => layer.open({
            type: 1,
            offset: 'r',
            anim: 'slideLeft',
            area: ['300px', '100%'],
            shade: 0.3,
            shadeClose: true,
            scrollbar: false,
            id: 'seting-id',
            title: '<i class="layui-icon-set layui-icon"></i>&nbsp;设置',
            content: $('#seting-content')
        }),
        'user-center': () => {
            form.val('user-center-form-filter', admin.getUser())
            layer.open({
                type: 1,
                title: '<i class="layui-icon-username layui-icon"></i>&nbsp;个人中心',
                offset: 'r',
                anim: 'slideLeft',
                shade: 0.3,
                area: ['500px', '100%'],
                shadeClose: true,
                scrollbar: false,
                id: 'user-center-id',
                content: $('#user-center-content')
            })
        },
        'reset-pwd': () => layer.open({
            type: 1,
            title: '<i class="layui-icon-username layui-icon"></i>&nbsp;密码设置',
            offset: 'r',
            anim: 'slideLeft',
            shade: 0.3,
            area: ['500px', '100%'],
            shadeClose: true,
            scrollbar: false,
            id: 'reset-pwd-id',
            content: $('#reset-pwd-content')
        }),
        'menu-fold': () => {
            let iconDom = $('.fold>.layui-icon')
            if (iconDom.hasClass('layui-icon-shrink-right')) {
                iconDom.removeClass('layui-icon-shrink-right')
                iconDom.addClass('layui-icon-spread-left')
                admin.hideMenu()
            } else {
                iconDom.removeClass('layui-icon-spread-left')
                iconDom.addClass('layui-icon-shrink-right')
                admin.showMenu()
            }
        },
        'logout': () => admin.confirm('确定退出系统吗？', () => admin.postM('sys/user/logout', undefined, () => (admin.removeToken(), window.location.href = '/login.html')), '退出提示')
    })

    /*监听：页脚显隐切换*/
    form.on('switch(footer-filter)', e => {
        let show = $(e.othis[0]).hasClass('layui-form-onswitch')
        admin.postM('sys/user/footer/' + show, undefined, () => admin.setFooter(show))
    })

    form.on('submit(submit-user-center-form)', ({field}) => {
        admin.postM('sys/user/update', field, () => {
            $('#user>i').first().attr('class', 'layui-icon layui-icon-' + field.sex)
            $('#user>span').text(field.realname)
            admin.setUser(field)
            layer.closeAll('page')
        })

        return false;
    })

    form.on('submit(submit-reset-pwd-form)', ({field}) => {

        if (field.newpwd != field.confirmpwd) {
            layer.msg('两次密码输入不一致')
            return false
        }
        admin.postM('sys/user/reset_pwd', field, () => admin.post('sys/user/logout', undefined, () => {
            admin.removeToken()
            window.location.href = '/login.html'
        }))

        return false;
    })
});